# websocket_manager.py
import websockets
import json
from fastapi import WebSocket
from typing import List

class WebSocketManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        """处理新的 WebSocket 连接"""
        await websocket.accept()
        self.active_connections.append(websocket)

    async def disconnect(self, websocket: WebSocket):
        """处理 WebSocket 断开"""
        self.active_connections.remove(websocket)
        await websocket.close()

    async def send_personal_message(self, message: bytes, websocket: WebSocket):
        """向单个连接发送消息"""
        await websocket.send_bytes(message)

    async def broadcast(self, message: bytes):
        """广播消息给所有连接的 WebSocket 客户端"""
        for connection in self.active_connections:
            await connection.send_bytes(message)

    async def notify_clients(self, message: dict):
        """向所有连接的 WebSocket 客户端发送通知消息"""
        json_message = json.dumps(message)
        for connection in self.active_connections:
            await connection.send_text(json_message)

manager =WebSocketManager()